//
//  TransitionAnimator.m
//  test
//
//  Created by 科迈捷 on 2017/4/1.
//  Copyright © 2017年 科迈捷. All rights reserved.
//

#import "TransitionAnimator.h"

@interface TransitionAnimator ()<CAAnimationDelegate> {
    void(^callback)();
}

@end
@implementation TransitionAnimator
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext {
    return 1;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext {
    //从上下文中获取必需信息
    UIView *fromV = [transitionContext viewForKey:UITransitionContextFromViewKey];
    UIView *toV = [transitionContext viewForKey:UITransitionContextToViewKey];
    UIView *containerView = [transitionContext containerView];
    //将视图添加到containerView中
    [containerView addSubview:fromV];
    [containerView addSubview:toV];
    
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGPoint tempPoint = [containerView convertPoint:self.touchPoint fromView:[transitionContext viewForKey:UITransitionContextFromViewKey]];
    CGRect rect = CGRectMake(tempPoint.x-1, tempPoint.y-1, 2, 2);
    
    //使用UIBerizerPath绘制动画的开始路径和结束路径
    UIBezierPath *startPath = [UIBezierPath bezierPathWithOvalInRect:rect];
    UIBezierPath *endPath = [UIBezierPath bezierPathWithArcCenter:containerView.center radius:sqrt(screenHeight * screenHeight + screenWidth * screenWidth) startAngle:0 endAngle:M_PI*2 clockwise:YES];
    
    //设置maskLayer
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = startPath.CGPath;
    toV.layer.mask = maskLayer;
    
    //设置动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
    animation.delegate = self;
    animation.fromValue = (id)startPath.CGPath;
    animation.toValue = (id)endPath.CGPath;
    animation.duration = [self transitionDuration:transitionContext];
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    [maskLayer addAnimation:animation forKey:@"custom"];
    callback = ^ {
        toV.layer.mask = nil;
        [maskLayer removeAnimationForKey:@"custom"];
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
    };
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    callback();
}


@end
